import os

from PyQt5.QtCore import Qt, QPoint, QThread, pyqtSignal
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout
from qfluentwidgets import CardWidget, IconWidget, BodyLabel, CaptionLabel, PushButton, TransparentToolButton, \
    FluentIcon, Action, RoundMenu, InfoBar, InfoBarPosition

from ..components.configPathMessageBox import ConfigPathMessageBox
from ..utils.checkDevLanguageVersion import checkVersionForDevLanguage


class VersionCheckThread(QThread):
    version_signal = pyqtSignal(str)

    def __init__(self, name):
        super().__init__()
        self.name = name

    def run(self):
        try:
            version = checkVersionForDevLanguage(self.name)
        except Exception as e:
            version = ""
        self.version_signal.emit(version)


class DevLanguageItem(CardWidget):
    """ DevLanguageItem card """

    def __init__(self, devLanguage, parent=None):
        super().__init__(parent)
        self.devLanguage = devLanguage
        self.setContentsMargins(0, 0, 0, 0)
        self.iconWidget = IconWidget(devLanguage.icon)
        self.envLanguageLabel = BodyLabel(devLanguage.name, self)
        self.contentLabel = CaptionLabel("未安装", self)
        self.mainButton = PushButton('安装', self)
        self.moreButton = TransparentToolButton(FluentIcon.MORE, self)

        self.hBoxLayout = QHBoxLayout(self)
        self.vBoxLayout = QVBoxLayout()

        self.setFixedHeight(73)
        self.setMinimumSize(500, 73)
        self.iconWidget.setFixedSize(48, 48)
        self.contentLabel.setTextColor("#606060", "#d2d2d2")
        self.mainButton.setFixedWidth(120)
        self.mainButton.setEnabled(self.isExistEnvPath())

        self.hBoxLayout.setContentsMargins(15, 15, 15, 15)
        self.hBoxLayout.setSpacing(15)
        self.hBoxLayout.addWidget(self.iconWidget)

        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.setSpacing(0)
        self.vBoxLayout.addWidget(self.envLanguageLabel, 0, Qt.AlignVCenter)
        self.vBoxLayout.addWidget(self.contentLabel, 0, Qt.AlignVCenter)
        self.vBoxLayout.setAlignment(Qt.AlignVCenter)
        self.hBoxLayout.addLayout(self.vBoxLayout)

        self.hBoxLayout.addStretch(1)
        self.hBoxLayout.addWidget(self.mainButton, 0, Qt.AlignRight)
        self.hBoxLayout.addWidget(self.moreButton, 0, Qt.AlignRight)

        self.moreButton.setFixedSize(32, 32)

        self.mainButton.clicked.connect(self.__onMainButtonClicked)
        self.moreButton.clicked.connect(self.__onMoreButtonClicked)

        self.version_thread = VersionCheckThread(self.devLanguage.name)
        self.version_thread.version_signal.connect(self.handle_version)
        self.getCurrentEnvVersion()

    def getCurrentEnvVersion(self):
        self.version_thread.start()

    def isExistEnvPath(self):
        if self.devLanguage.env_var_value and os.path.exists(self.devLanguage.env_var_value):
            return True
        else:
            return False

    def handle_version(self, version):
        # 在这里更新你的 GUI
        self.devLanguage.version = version
        if version:
            self.contentLabel.setText("已安装版本信息：" + version)
            if self.isExistEnvPath():
                self.mainButton.setText("重新安装")
            else:
                self.mainButton.setText("未配置")
        else:
            self.contentLabel.setText("未安装")
            self.mainButton.setText("安装")

    def __onMainButtonClicked(self):
        try:
            isInstall = self.devLanguage.install_env()
            if isInstall:
                InfoBar.success(
                    title='安装成功！',
                    content='请重启软件或新建一个cmd窗口进行校验！',
                    orient=Qt.Vertical,
                    isClosable=True,
                    position=InfoBarPosition.BOTTOM_RIGHT,
                    duration=3000,
                    parent=self.parent().parent()
                )
                self.contentLabel.setText("已安装版本信息：" +
                                          checkVersionForDevLanguage(
                                              self.devLanguage.name,
                                              self.devLanguage.env_var_value
                                          ))
            else:
                InfoBar.warning(
                    title='安装失败！',
                    content='请检查配置路径是否正确！',
                    orient=Qt.Vertical,
                    isClosable=True,
                    position=InfoBarPosition.BOTTOM_RIGHT,
                    duration=3000,
                    parent=self.parent().parent()
                )
        except FileNotFoundError:
            InfoBar.error(
                title='安装路径不对劲！',
                content=FileNotFoundError.__str__(),
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                duration=3000,
                parent=self.parent().parent()
            )
        except Exception as e:
            InfoBar.error(
                title='出错啦！',
                content=e.__str__(),
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                duration=3000,
                parent=self.parent().parent()
            )

    def __onMoreButtonClicked(self):
        menu = RoundMenu(parent=self)
        configAction = Action(FluentIcon.SETTING, '配置', self)
        menu.addAction(configAction)
        configAction.triggered.connect(self.__configActionEvent)

        x = (self.moreButton.width() - menu.width()) // 2 + 10
        pos = self.moreButton.mapToGlobal(QPoint(x, self.moreButton.height()))
        menu.exec(pos)

    def __configActionEvent(self):
        w = ConfigPathMessageBox(self.devLanguage, self.window())
        if w.exec():
            try:
                # 将env_value写入config.json
                self.devLanguage.setEnvValToConfig()
                InfoBar.success(
                    title='保存配置成功！',
                    content=f'配置路径: {w.pathLineEdit.text()}',
                    orient=Qt.Vertical,
                    isClosable=True,
                    position=InfoBarPosition.BOTTOM_RIGHT,
                    duration=3000,
                    parent=self.parent().parent()
                )
                # 更新界面
                self.mainButton.setEnabled(self.isExistEnvPath())
            except Exception as e:
                print(e)
                InfoBar.warning(
                    title='错误！',
                    content=e.__str__(),
                    orient=Qt.Vertical,
                    isClosable=True,
                    position=InfoBarPosition.BOTTOM_RIGHT,
                    duration=3000,
                    parent=self.parent().parent()
                )
